package replicated_calculator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;


/**
 *
 * Rudimentary implementation of a Textual User Interface for a 
 * DistributedCalculator client.
 *
 * @author Jesper Buus Nielsen, Aarhus University, 2012.
 *
 */

public class ServerTUI {

    synchronized public static void report(String str) {
        System.out.println(str);
    }

    public static void main(String[] args) {
        /**
         * Here you would instantiation your own, more impressive server instead.
         */
        Server server = new ServerReplicated();

        try {
            // For reading from standard input
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
            String s;

            report("Exit: Gracefully logs out");
            report("Crash: Makes the server crash.");
            report("");

            /*
            * Get the address of a server.
            */
            String serverAddress = null;
            System.out.print("Enter address of another server (ENTER for standalone)(Leave out port for default): ");
            if ((s = stdIn.readLine()) != null) {
                serverAddress = s;
            } else {
                return;
            }

            if (s.equals("")) {
                server.createGroup(Parameters.mainServerPortForServers);
            } else {
                String address = serverAddress;
                int port = Parameters.mainServerPortForServers;
                if(serverAddress.indexOf(':') != -1){
                    address = serverAddress.substring(0, serverAddress.indexOf(':'));
                    port = Integer.parseInt(serverAddress.substring(serverAddress.indexOf(':')+1));
                }
                if(address.toLowerCase().equals("localhost")){
                    address = InetAddress.getLocalHost().getCanonicalHostName();
                }


                System.out.print("Enter port for listening (ENTER for default): ");
                if ((s = stdIn.readLine()) == null) {
                    return;
                }
                if (!s.equals("")) {
                    int serverPort = Integer.parseInt(s);
                    server.setListenPort(serverPort, serverPort-2000);
                }
                server.joinGroup(new InetSocketAddress(address,port));
            }

            while ((s = stdIn.readLine()) != null) {
                if (s.equals("Crash")) {
                    System.exit(-1);
                } else if (s.equals("Exit")) {
                    server.leaveGroup();
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Shutting down the server!");
    }

}
